package download;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import util.FileAccess;
import util.Utility;


public class DownloadThread extends Thread
{

	private String URL; // File URL
	private long startPos; // File Start Position
	private long endPos; // File End Position
	private int threadID; // Thread's ID
	private boolean downOver = false; // Downing is over
	private boolean stop = false; // Stop identical
	FileAccess fileAccess = null; // File Access interface

	public DownloadThread(String URL, String filePath, long start, long end, int id) throws IOException
	{
		this.URL = URL;
		this.startPos = start;
		this.endPos = end;
		threadID = id;
		fileAccess = new FileAccess(filePath, startPos);
	}

	public void run()
	{
		try
		{
			URL url = new URL(URL);
			HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection.setRequestProperty("User-Agent", "NetFox");
			String sProperty = "bytes=" + startPos + "-";
			httpConnection.setRequestProperty("RANGE", sProperty);
			Utility.log(sProperty);
			InputStream input = httpConnection.getInputStream();

			byte[] b = new byte[1024];
			int nRead;
			while ((nRead = input.read(b, 0, 1024)) > 0 && startPos < endPos && !stop)
			{
				startPos += fileAccess.write(b, 0, nRead);
			}
			
			Utility.log("Thread " + threadID + " is over!");
			downOver = true;
			fileAccess.close();
			fileAccess = null;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	// ��ӡ��Ӧ��ͷ��Ϣ
	public void logResponseHead(HttpURLConnection con)
	{
		for (int i = 1;; i++)
		{
			String header = con.getHeaderFieldKey(i);
			if (header != null)
				Utility.log(header + " : " + con.getHeaderField(header));
			else
				break;
		}
	}

	public void threadStop()
	{
		stop = true;
	}

	public boolean isDownOver()
	{
		return downOver;
	}

	public void setDownOver(boolean downOver)
	{
		this.downOver = downOver;
	}

	public long getStartPos()
	{
		return startPos;
	}

	public long getEndPos()
	{
		return endPos;
	}

}
